<template>
	<view class="page-container">
		<!-- 头部背景 -->
		<view class="header">
			<view class="user-info">
				<view class="user-avatar" @click="gotoLogin()">
					<!-- 增加头像占位符逻辑 -->
					<image v-if="userAvatar" :src="userAvatar" mode="aspectFill"></image>
					<image v-else src="@/static/mine/avatar.png" mode="aspectFill"></image>
				</view>
				<view class="user-details" @click="gotoLogin()">
					<view class="username">{{ username }}
						<image src="../../static/public/right_arrow.png" mode="widthFix" v-if="this.user"></image>
					</view>
					<view class="account" v-if="this.user">账号: {{ account }}</view>
					<view class="user-stats">
						<view class="stat-item">
							<view class="stat-value">{{ followers }}</view>
							<view class="stat-label">关注</view>
						</view>
						<view class="stat-item">
							<view class="stat-value">{{ fans }}</view>
							<view class="stat-label">粉丝</view>
						</view>
						<view class="stat-item">
							<view class="stat-value">{{ likes }}</view>
							<view class="stat-label">获赞</view>
						</view>
					</view>
				</view>
				<view class="user-setup">
					<image src="@/static/mine/customer_service.png" mode="widthFix" @click="tuichudenglu()"></image>
					<image src="@/static/mine/settings.png" mode="widthFix"></image>
				</view>
			</view>

			<view class="user-profile">
				<view>{{ shortProfile }}</view>
			</view>
			<view class="user-meta" v-if="this.user">
				<view class="meta-item">IP {{ ipLocation }}</view>
				<view class="meta-item">
					<image src="@/static/public/male.png" mode="widthFix"></image>
				</view>
				<view class="meta-item">
					<view class="age">{{ age }}岁</view>
				</view>
				<view class="meta-item" v-if="this.user.standing != null">
					已实名
				</view>
				<view class="meta-item" v-else @click="skipStanding()">
					未实名
				</view>
			</view>
		</view>

		<!-- 按钮列表 -->
		<view class="button-list" v-if="this.user">
			<view class="button-item">
				<image src="@/static/mine/order.png" mode="aspectFit"></image>
				<view class="label">全部订单</view>
			</view>
			<view class="button-item">
				<image src="@/static/mine/purse.png" mode="aspectFit"></image>
				<view class="label">我的钱包</view>
			</view>
			<view class="button-item">
				<image src="@/static/mine/credit.png" mode="aspectFit"></image>
				<view class="label">信用分</view>
			</view>
			<view class="button-item">
				<image src="@/static/mine/after_sale.png" mode="aspectFit"></image>
				<view class="label">售后中心</view>
			</view>
			<view class="button-item" @click="skipStanding()">
				<image src="@/static/mine/more.png" mode="aspectFit"></image>
				<view class="label">更多</view>
			</view>
		</view>

		<!-- 标签导航 -->
		<view class="nav-tabs">
			<view class="tab-item" :class="{ active: currentTab === '动态' }" @click="switchTab('动态')">动态</view>
			<view class="tab-item" :class="{ active: currentTab === '任务' }" @click="switchTab('任务')">任务</view>
			<view class="tab-item" :class="{ active: currentTab === '商品' }" @click="switchTab('商品')">商品</view>
			<view class="tab-item" :class="{ active: currentTab === '喜欢' }" @click="switchTab('喜欢')">喜欢</view>
			<view class="tab-item" :class="{ active: currentTab === '评价' }" @click="switchTab('评价')">评价</view>
		</view>

		<!-- 论坛帖子 -->
		<view class="timeline" v-show="currentTab === '动态'&&this.newList.length!==0">
			<view v-for="(item, index) in newList" :key="index" class="item">
				<view class="date">
					<view class="month">{{ formatCreateDay(item.createTime) }}</view>
					<view class="day">{{ formatCreateMonth(item.createTime) }}</view>
				</view>
				<view class="content">
					<view class="content-album">
						<u-album :rowCount="calculatedRowCount(item.picture)" :maxCount="9" :space="4" :singleSize='100'
							:multipleSize="calculatedMultipleSize(item.picture)" :urls="item.picture"
							style="width: 100%;" v-if="item.picture.length>1"></u-album>
						<image v-if="item.picture.length==1" :src="item.picture[0]" style="width: 75px; height: 75px;"
							mode="aspectFill"></image>
					</view>
					<view class="detail" @click="isDetail=true">{{ shortContent(item.content) }}</view>
				</view>
				<image class="dot" src="@/static/mine/point.png"></image>
			</view>
		</view>
		<!--任务列表-->
		<view class="quest" v-show="currentTab === '任务'">
			<view v-for="(item,index) in questList" :key="index" @click="details(item)">
				<view>
					<view>
						<span>
							<image src="../../static/mine/time.png"></image>{{ calculationTime(item.cutoffTime) }}
						</span>
					</view>
					<view>

					</view>
					<view>
						<b>￥{{ item.price }}</b>
					</view>
				</view>
				<view>
					<view class="quest-title">{{ item.title }}</view>
				</view>
				<view class="quest-time">
					<image src="../../static/mine/time.png"></image>
					{{ formatDate(item.createTime) }}
				</view>
				<view>
					<view>
						<span v-if="item.address.coordinate == null">
							线上需求
						</span>
						<span v-else>
							<image src="@/static/public/orientation.png" alt="定位" mode="heightFix" />
							{{ getMapDistance(item.address.coordinate) }}km
							<span style="display: inline-block;width: 2vw;"></span>
							{{ item.address.name }}
						</span>
					</view>
					<view>{{ item.initiator.name }}</view>
				</view>
			</view>
		</view>
		<u-loadmore v-show="this.user" :status="status" dashed line />
		<view style="width: 100vw;height: 1vh; opacity: 0;"></view>
	</view>
</template>

<script>
	import {
		rear
	} from '@/config/api.js';

	export default {
		data() {
			return {
				userAvatar: '', // 用户头像URL
				username: '点击登录',
				account: '',
				followers: 0,
				fans: 0,
				likes: 0,
				ipLocation: '',
				profile: "",
				age: 0,
				isDetail: false,
				currentTab: '动态', // 当前激活的标签
				timelineItems: [],
				user: {},
				pos: {
					latitude: 0,
					longitude: 0,
				},
				status: "nomore",
				questList: [],
				newList: [],
				questPage: {
					userId: 0,
					current: 0,
					pageSize: 15,
					total: 0
				},
				newPage: {
					userId: 0,
					current: 0,
					pageSize: 7,
					total: 0
				}
			};
		},
		onReachBottom() {
			if (this.questList.length === this.questPage.total || this.newList.length === this.newPage.total) {
				this.status = "nomore";
			}
			if (this.user.id != null) {
				if (this.questPage.total > this.questList.length && this.currentTab === '任务') {
					this.status = "loading";
					this.questPage.current++
					this.getInitiatorList(this.user.id);
				}
				if (this.newPage.total > this.newList.length && this.currentTab === '动态') {
					this.status = "loading";
					this.newPage.current++
					this.getTweetByUserId(this.user.id);
				}
			}
		},
		onShow() {
			this.user = uni.getStorageSync('user');
			if (this.user.id != null) {
				if (this.questList.length === 0) {
					this.getTweetTotal(this.user.id);
					this.getInitiatorTotal(this.user.id);
					this.getInitiatorList(this.user.id);
					this.getTweetByUserId(this.user.id);
				}
				this.userAvatar = this.user.avatar;
				this.username = this.user.name;
				this.account = this.user.account;
				this.followers = this.user.followers || 0;
				this.fans = this.user.fans || 0;
				this.likes = this.user.likes || 0;
				this.ipLocation = this.user.city.detailsName == '' || this.user.city.detailsName == null ? '未知' : this.user
					.city.detailsName
				this.profile = this.user.intro || '';
				this.age = this.user.birthday ? new Date().getFullYear() - new Date(this.user.birthday).getFullYear() : 0;
			} else {
				this.userAvatar = '', // 用户头像URL
					this.username = '点击登录',
					this.questList = [],
					this.newList = [],
					this.account = '',
					this.followers = 0,
					this.fans = 0,
					this.likes = 0,
					this.ipLocation = '',
					this.profile = "",
					this.age = 0
			}
		},
		onLoad() {
			uni.getLocation({
				success: res => {
					this.pos = res;
				}
			});
		},
		methods: {
			skipStanding() {
				if (this.city == "请登录") {
					uni.showToast({
						title: '请登录',
						icon: 'none',
						duration: 2000,
					});
					uni.navigateTo({
						url: '/pages/mine/login'
					});
				} else {
					uni.navigateTo({
						url: '/pages/standing/index'
					})
				}
			},
			tuichudenglu() {
				uni.removeStorageSync('user');
			},
			switchTab(tabName) {
				this.currentTab = tabName;
				if (this.questList.length === this.questPage.total || this.newList.length === this.newPage.total) {
					this.status = "nomore";
				}
			},
			getInitiatorList(id) {
				this.questPage.userId = id;
				uni.request({
					url: rear + "/quest/getInitiatorList", // API 地址
					method: 'GET', // 请求方法
					data: this.questPage,
					success: (res) => {
						this.questList.push(...res.data.data);
					}
				});
			},
			getInitiatorTotal(id) {
				uni.request({
					url: rear + "/quest/getInitiatorTotal", // API 地址
					method: 'GET', // 请求方法
					data: {
						userId: id
					},
					success: (res) => {
						this.questPage.total = res.data.data;
					}
				});
			},
			getTweetTotal(id) {
				uni.request({
					url: rear + "/tweet/getTweetTotalByUserId", // API 地址
					method: 'GET', // 请求方法
					data: {
						userId: id
					},
					success: (res) => {
						this.newPage.total = res.data.data;
					}
				});
			},
			getTweetByUserId(id) {
				this.newPage.userId = id;
				uni.request({
					url: rear + "/tweet/getTweetByUserId", // API 地址
					method: 'GET', // 请求方法
					data: this.newPage,
					success: (res) => {
						this.newList.push(...res.data.data);
					}
				});
			},
			formatCreateMonth(createTime) {
				const date = new Date(createTime);
				const month = date.getMonth() + 1;
				const day = date.getDate();
				const formattedMonth = month < 10 ? `0${month}` : month;
				const formattedDay = day < 10 ? `0${day}` : day;
				return `${formattedMonth}月`;
			},
			formatCreateDay(createTime) {
				const date = new Date(createTime);
				const month = date.getMonth() + 1;
				const day = date.getDate();
				const formattedMonth = month < 10 ? `0${month}` : month;
				const formattedDay = day < 10 ? `0${day}` : day;
				return `${formattedDay}`;
			},
			onOperate(index) {
				if (uni.getStorageSync('user').id == null || uni.getStorageSync('user').id == "") {
					uni.showToast({
						title: '请登录',
						icon: 'none',
						duration: 2000,
					});
					uni.navigateTo({
						url: '/pages/mine/login'
					});
				} else {
					uni.request({
						url: rear + "/praise/controlsPraise",
						method: "POST",
						data: {
							"contentId": this.newList[index].id,
							"type": 0,
							"userId": this.user.id
						},
						success: (res) => {
							if (res.data.data) {
								this.newList[index].isPraise = !this.newList[index].isPraise;
								if (this.newList[index].isPraise) {
									this.newList[index].praiseNum++;
								} else {
									this.newList[index].praiseNum--;
								}
							}
						}
					})
				}
			},
			getSR(birthday) {
				const time = new Date(birthday).getTime();
				const time2 = new Date().getTime();
				const a = time2 - time;
				const b = Math.floor(a / (1000 * 60 * 60 * 24 * 365))
				return b
			},
			gotoLogin() {
				if (this.user) {
					return;
				}
				uni.navigateTo({
					url: '/pages/mine/login'
				});
			},
			calculatedRowCount(count) {
				let rowCount = 3;
				if (count.length === 2 || count.length === 4) {
					rowCount = 2;
				}
				return rowCount;
			},
			calculatedMultipleSize(count) {
				let rowSize = 30;
				if (count.length === 2 || count.length === 4) {
					rowSize = 45;
				}
				return rowSize;
			},
			calculationTime(time) {
				let currentTime = new Date(time).getTime() - new Date().getTime(); //当前时间
				let totalSeconds = Math.floor(currentTime / 1000);
				let days = Math.floor(totalSeconds / (3600 * 24));
				let hours = Math.floor((totalSeconds % (3600 * 24)) / 3600);
				let minutes = Math.floor((totalSeconds % 3600) / 60);
				let text = "";
				if (days != 0) {
					text = days + "天"
				}
				if (hours != 0) {
					text += hours + "小时"
				} else if (text != "") {
					text += "0小时"
				}
				if (minutes != 0) {
					text += minutes + "分钟";
				}
				return text + "后截止"
			},
			getMapDistance(coordinate) {
				const lat1 = +this.pos.latitude;
				const lat2 = parseFloat(coordinate.split(",")[1]);
				const lon1 = +this.pos.longitude;
				const lon2 = parseFloat(coordinate.split(",")[0]);
				const R = 6378137;
				let radLat1 = lat1 * Math.PI / 180.0;
				let radLat2 = lat2 * Math.PI / 180.0;
				let radLon1 = lon1 * Math.PI / 180.0;
				let radLon2 = lon2 * Math.PI / 180.0;
				// 计算两点间的弧度差
				let a = radLat1 - radLat2;
				let b = radLon1 - radLon2;
				// Haversine 公式
				let s = 2 * R * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
					Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
				return (s / 1000).toFixed(1); // 返回距离，单位为千米
			},
			formatDate(isoString) {
				const date = new Date(isoString);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			shortContent(content) {
				if (content.length > 25) {
					return content.slice(0, 25) + '...';
				}
				return content;
			},
			details(item) {
				if (uni.getStorageSync('user').id == null || uni.getStorageSync('user').id == "") {
					uni.showToast({
						title: '请登录',
						icon: 'none',
						duration: 2000,
					});
					uni.navigateTo({
						url: '/pages/mine/login'
					});
				} else {
					uni.setStorageSync('questId', item.id);
					uni.navigateTo({
						url: '/pages/home/details',
					});
				}
			},
		},
		computed: {
			shortProfile() {
				if (this.profile.length > 50) {
					return this.profile.slice(0, 50) + '...';
				}
				return this.profile;
			}
		},
	};
</script>

<style lang="scss" scoped>
	/* 颜色和样式变量 */
	$primary-color: #ff4b4b;
	$secondary-color: #666;
	$light-background: #f6f5f4;

	.page-container {
		background: url("@/static/public/background.png") #FCFBFA no-repeat;
		background-size: cover;
		width: 100vw;
		height: 100vh;
	}

	.user-profile {
		display: flex;
		flex-direction: column;
		text-align: left;
		color: $secondary-color;
		margin: 0 auto;
		border-top: 0.3vw solid rgba(100, 100, 100, 0.1);
		width: 90vw;
	}

	/* 头部样式 */
	.header {
		padding: 2vh 0;
		text-align: center;
		border-radius: 1vh;
	}

	.user-setup {
		position: fixed;
		top: 6vh;
		right: 1vh;

		image {
			width: 2.2vh;
			margin-left: 1vh;
		}
	}

	.user-info {
		margin-top: 8vh;
		position: relative;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		padding: 0 4vw;
	}

	.user-avatar {
		width: 8vh;
		height: 8vh;
		border-radius: 50%;
		overflow: hidden;
		margin-right: 2vw;
		position: relative;
		top: -1.5vh;
		z-index: 11111;
	}

	.user-avatar image {
		width: 100%;
		height: 100%;
	}

	.user-details {
		text-align: left;
	}

	.username {
		font-size: 2.2vh;
		font-weight: bold;
		color: #333;
		margin-top: 20px;
		display: flex;
		align-items: center;

		image {
			width: 5px;
			margin-left: 6px;
		}
	}

	.account {
		font-size: 1.8vh;
		color: #999;
		margin-top: 1vh;
	}

	.user-stats {
		display: flex;
		justify-content: flex-start;
		margin: 1.5vh 0;

	}

	.stat-item {
		display: flex;
		padding: 0 1vw;
		align-items: center;
		flex-direction: row;
		justify-content: space-between;
	}

	.stat-value {
		font-size: 2vh;
		font-weight: bold;
		color: #333;
		margin-right: 1vw;
	}

	.stat-label {
		font-size: 1.8vh;
		color: #999;
	}

	.user-meta {
		display: flex;
		justify-content: flex-start;
		margin-left: 0;
		align-items: center;
		width: 90vw;
		margin: 0 auto;
		margin-top: 1vh;
	}

	.meta-item {
		font-size: 1.6vh;
		color: #999;
		margin-right: 2vw;
		background-color: #F2F1F1;
		border-radius: 1vh;
		padding: 0 0.5vh;

		image {
			width: 1.5em;
			vertical-align: -0.2em;
		}
	}

	.age {
		background-color: #F2F1F1;
		border-radius: 1vh;
	}

	/* 按钮列表 */
	.button-list {
		display: flex;
		justify-content: space-around;
		background-color: white;
		border-radius: 1vh;
		padding: 1.5vh 0;
		width: 90vw;
		margin: 0 auto;
		margin-bottom: 2vh;
	}

	.button-item {
		flex: 1;
		text-align: center;
		max-width: 20vw;
		/* 保持按钮宽度一致 */

		image {
			width: 3vh;
			height: 3vh;
			z-index: 111;
		}
	}

	.label {
		font-size: 1.8vh;
		color: $secondary-color;
	}

	/* 标签导航 */
	.nav-tabs {
		display: flex;
		justify-content: space-around;
		background-color: white;
		border-radius: 1vh;
		padding: 1vh 0;
		width: 90vw;
		margin: 0 auto;
		margin-bottom: 1vh;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		font-size: 1.8vh;
		color: $secondary-color;
		padding: 0.5vh 0;
		position: relative;
		cursor: pointer;
	}

	.tab-item.active {
		color: $primary-color;
		font-weight: bold;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		width: 15vw;
		height: 0.3vh;
		background-color: $primary-color;
		bottom: -0.5vh;
		left: 50%;
		transform: translateX(-50%);
		transition: width 0.3s ease;
	}

	/* 动态列表 */
	.timeline {
		background-color: white;
		border-radius: 1vh;
		width: 90vw;
		margin: 0 auto;
		padding: 1.5vh;
	}

	.timeline .item {
		position: relative;
		left: -4vw;
		display: flex;
		padding: 1vh 0;
		flex-direction: column;
		width: 80%;
		border-left: 2px solid #E4E4E4;
		margin: 0 auto;
		padding-left: 5%;
		position: relative;

		.dot {
			width: 2vh;
			height: 2vh;
			position: absolute;
			left: -3%;
			top: -1%;
		}

	}

	.timeline .item:last-child {
		border-bottom: none;
	}

	.timeline .date {
		font-size: 1.6vh;
		color: #333;
		font-weight: bold;
		white-space: nowrap;
		overflow: hidden;
		position: relative;
		top: -3.5vw;
		text-overflow: ellipsis;
		max-width: 80%;

		.month {
			font-size: 2.5vh;
			margin-right: 1vw;
		}

		view {
			display: inline-block;
		}
	}

	.timeline .content {
		position: relative;
		top: -3vw;
		margin-left: 2vw;
		font-size: 1.6vh;
		display: flex;
		width: 70vw;

		.album {
			width: 30vw;
		}

		.detail {
			font-size: 1.8vh;
			margin-bottom: 1vw;
			width: 40vw;
			margin-left: 2vw;
		}
	}

	.timeline .title {
		font-size: 1.8vh;
		margin-bottom: 1vw;
		color: #999;

	}

	.timeline .price {
		font-size: 1.8vh;
		color: $primary-color;
	}

	//任务样式
	.quest {
		width: 90vw;
		margin: 0 auto;

		.quest-time {
			position: relative;
			bottom: -1.2vw;

			image {
				width: 3vw;
				height: 3vw;
				margin-right: 0.5vw;
			}
		}

		.quest-title {
			margin: 1vw 0;
		}

		>view {
			background-color: #FFFFFF;
			box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
			border-radius: 3vw;
			margin-bottom: 3vw;
			padding: 3vw;

			>view:nth-of-type(1) {
				display: flex;
				flex-wrap: wrap;
				padding-bottom: 1vw;
				line-height: 6.5vw;
				justify-content: space-between;

				>view:nth-of-type(2) {
					width: 10%;

					image {
						width: 6.5vw;
						height: 6.5vw;
						border-radius: 3.25vw;
					}
				}

				>view:nth-of-type(3) {
					width: 40%;
					color: #FF0000;
					font-size: 5vw;
					text-align: right;
				}

				>view:nth-of-type(1) {
					width: 50%;
					text-align: right;
					display: flex;
					align-items: center;
					justify-content: space-between;
					position: absolute;
					left: 7vw;

					image {
						width: 3vw;
						height: 3vw;
						margin-right: 0.5vw;
					}

					span {
						display: inline-block;
						padding: 0 1.5vw;
						background-color: #FFEFEF;
						border-radius: 3.25vw;
						height: 6.5vw;
						text-align: center;
						color: #FE5C0B;
						font-size: 3vw;
					}
				}
			}

			>view:nth-of-type(3) {
				margin-top: 1vw;
				color: #AAAAAA;
				font-size: 3vw;
			}

			>view:nth-of-type(4) {
				height: 5vw;
				line-height: 5vw;
				padding-top: 1vw;
				display: flex;
				flex-wrap: wrap;
				color: #AAAAAA;

				>view:nth-of-type(1) {
					width: 60%;
					font-size: 3vw;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;

					image {
						height: 3vw;
						vertical-align: -0.3vw;
					}
				}

				>view:nth-of-type(2) {
					width: 40%;
					text-align: right;
					font-size: 3vw;
				}
			}
		}
	}

	.loading {
		text-align: center;

		image {
			width: 10vw;
		}
	}
</style>